package com.qf.filter;

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class PermFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String uriStr=request.getRequestURI();
        System.out.println("======="+uriStr);

        if(uriStr.lastIndexOf(".")>0) {
            String extStr = uriStr.substring(uriStr.lastIndexOf("."));
            if (extStr != null) {
                if (".js".equals(extStr)) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }
        if(uriStr.contains("/login")||uriStr.contains("/code")
                ||uriStr.contains("/goods")
                ||uriStr.contains("/admin")
                ||uriStr.contains("/type")
                ||uriStr.contains("/register")
                ||uriStr.contains("/user")
                ||uriStr.contains("/index.jsp")
                ||uriStr.contains(".css")
                ||uriStr.contains(".jsp")||uriStr.contains(".png")
                ||uriStr.contains(".gif")||uriStr.contains(".eot")
                ||uriStr.contains(".svg")||uriStr.contains(".ttf")
                ||uriStr.contains(".woff")||uriStr.contains(".woff2")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        HttpSession session = request.getSession();
        User user= (User) session.getAttribute("loginUser");
        if(user!=null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            response.sendRedirect("/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
